<template>
  <div class="reviewed-resume-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2 class="title">已审批简历列表</h2>
          <div class="header-actions">
            <el-button @click="refreshList" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-bar">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-select
              v-model="filters.status"
              placeholder="审核状态"
              clearable
              @change="handleFilterChange"
            >
              <el-option label="全部" value="" />
              <el-option label="审核通过" value="approved" />
              <el-option label="审核未通过" value="rejected" />
              <el-option label="需要修改" value="needs_revision" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleFilterChange"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="filters.keyword"
              placeholder="搜索简历标题或学生姓名"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleFilterChange">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilters">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 统计信息 -->
      <div class="statistics">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-statistic title="总计" :value="statistics.total" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="审核通过" :value="statistics.approved" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="审核未通过" :value="statistics.rejected" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="需要修改" :value="statistics.needs_revision" />
          </el-col>
        </el-row>
      </div>

      <!-- 简历列表 -->
      <el-table
        :data="resumeList"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="简历标题" min-width="200">
          <template #default="{ row }">
            <div class="resume-title">
              <span>{{ row.title }}</span>
              <el-tag
                v-if="row.resume_type === 'uploaded'"
                type="info"
                size="small"
                style="margin-left: 8px"
              >
                上传
              </el-tag>
              <el-tag
                v-else
                type="success"
                size="small"
                style="margin-left: 8px"
              >
                在线生成
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="student_name" label="学生姓名" width="120" />

        <el-table-column prop="status" label="审核状态" width="120">
          <template #default="{ row }">
            <ResumeStatusTag :status="row.status" />
          </template>
        </el-table-column>

        <el-table-column prop="completion_rate" label="完成度" width="100">
          <template #default="{ row }">
            <el-progress
              :percentage="row.completion_rate || 0"
              :stroke-width="6"
              :show-text="false"
              :status="getCompletionStatus(row.completion_rate)"
              style="width: 60px"
            />
            <span style="margin-left: 8px; font-size: 12px">
              {{ row.completion_rate || 0 }}%
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="reviewed_at" label="审核时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.reviewed_at) }}
          </template>
        </el-table-column>

        <el-table-column prop="reviewer_name" label="审核人" width="120" />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handlePreview(row)"
            >
              <el-icon><View /></el-icon>
              预览简历
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleViewReview(row)"
            >
              <el-icon><Document /></el-icon>
              查看审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 简历预览对话框 -->
    <EnhancedResumePreview
      v-if="currentResume"
      v-model:visible="showPreviewDialog"
      :resume-id="currentResume.id"
      :file-name="currentResume.title"
      :title="`预览简历 - ${currentResume.title}`"
    />

    <!-- 审核详情对话框 -->
    <el-dialog
      v-model="showReviewDialog"
      :title="`审核详情 - ${currentResume?.title}`"
      width="70%"
      top="5vh"
    >
      <div v-if="currentResume" class="review-detail">
        <!-- 基本信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h4>基本信息</h4>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="简历标题" :span="2">
              <div class="title-info">
                <span class="title-text">{{ currentResume.title }}</span>
                <el-tag
                  :type="currentResume.resume_type === 'uploaded' ? 'info' : 'success'"
                  size="small"
                  style="margin-left: 8px"
                >
                  {{ currentResume.resume_type === 'uploaded' ? '上传简历' : '在线生成' }}
                </el-tag>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="学生姓名">
              {{ currentResume.student_name }}
            </el-descriptions-item>
            <el-descriptions-item label="学生学号">
              {{ currentResume.student_id }}
            </el-descriptions-item>
            <el-descriptions-item label="简历完成度">
              <div class="completion-info">
                <el-progress
                  :percentage="currentResume.completion_rate || 0"
                  :stroke-width="6"
                  :status="getCompletionStatus(currentResume.completion_rate)"
                  style="width: 100px"
                />
                <span style="margin-left: 8px">{{ currentResume.completion_rate }}%</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatTime(currentResume.created_at) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 审核信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h4>审核信息</h4>
              <ResumeStatusTag :status="currentResume.status" />
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="审核状态">
              <div class="status-info">
                <ResumeStatusTag :status="currentResume.status" />
                <span class="status-desc">{{ getStatusDescription(currentResume.status) }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="审核时间">
              <div class="time-info">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(currentResume.reviewed_at) }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="审核人">
              <div class="reviewer-info">
                <el-icon><User /></el-icon>
                <span>{{ currentResume.reviewer_name || '系统自动' }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="处理时长">
              <div class="duration-info">
                <el-icon><Timer /></el-icon>
                <span>{{ getProcessingDuration(currentResume) }}</span>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 审核意见 -->
        <el-card class="detail-card" shadow="never" v-if="currentResume.review_comments">
          <template #header>
            <div class="card-header">
              <h4>审核意见</h4>
            </div>
          </template>
          <div class="comments-content">
            <div class="comments-text">
              {{ currentResume.review_comments }}
            </div>
          </div>
        </el-card>

        <!-- 操作历史 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h4>操作历史</h4>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-if="currentResume.reviewed_at"
              :timestamp="formatTime(currentResume.reviewed_at)"
              type="primary"
            >
              <div class="timeline-content">
                <div class="timeline-title">
                  <el-icon><Check /></el-icon>
                  <span>审核完成</span>
                </div>
                <div class="timeline-desc">
                  {{ currentResume.reviewer_name }} 完成了简历审核，结果：
                  <ResumeStatusTag :status="currentResume.status" />
                </div>
              </div>
            </el-timeline-item>
            <el-timeline-item
              :timestamp="formatTime(currentResume.updated_at)"
              type="success"
            >
              <div class="timeline-content">
                <div class="timeline-title">
                  <el-icon><Upload /></el-icon>
                  <span>简历提交</span>
                </div>
                <div class="timeline-desc">
                  学生提交简历进行审核
                </div>
              </div>
            </el-timeline-item>
            <el-timeline-item
              :timestamp="formatTime(currentResume.created_at)"
              type="info"
            >
              <div class="timeline-content">
                <div class="timeline-title">
                  <el-icon><Plus /></el-icon>
                  <span>简历创建</span>
                </div>
                <div class="timeline-desc">
                  学生创建了{{ currentResume.resume_type === 'uploaded' ? '上传' : '在线生成' }}简历
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlePreview(currentResume)">
            <el-icon><View /></el-icon>
            预览简历
          </el-button>
          <el-button @click="showReviewDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import {
  Search,
  Refresh,
  View,
  Document,
  Clock,
  User,
  Timer,
  Check,
  Upload,
  Plus
} from '@element-plus/icons-vue'
import { resumeApi, type Resume } from '@/api/resume'
import { formatTime } from '@/utils/format'
import EnhancedResumePreview from '@/components/EnhancedResumePreview.vue'
import ResumeStatusTag from '@/components/ResumeStatusTag.vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const loading = ref(false)
const showPreviewDialog = ref(false)
const showReviewDialog = ref(false)
const currentResume = ref<Resume | null>(null)
const resumeList = ref<Resume[]>([])

// 筛选条件
const filters = reactive({
  status: '',
  dateRange: null as [string, string] | null,
  keyword: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 统计信息
const statistics = reactive({
  total: 0,
  approved: 0,
  rejected: 0,
  needs_revision: 0
})

// 获取已审批简历列表
const fetchReviewedResumeList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      status: filters.status || undefined,
      start_date: filters.dateRange?.[0] || undefined,
      end_date: filters.dateRange?.[1] || undefined,
      search: filters.keyword || undefined,
      reviewed: true // 只获取已审批的简历
    }

    const response = await resumeApi.getTeacherResumeList(params)
    const data = response.data

    resumeList.value = data.results || []
    pagination.total = data.count || 0

    // 更新统计信息
    updateStatistics()
  } catch (error) {
    console.error('获取已审批简历列表失败:', error)
    ElMessage.error('获取简历列表失败')
  } finally {
    loading.value = false
  }
}

// 更新统计信息
const updateStatistics = () => {
  statistics.total = resumeList.value.length
  statistics.approved = resumeList.value.filter(r => r.status === 'approved').length
  statistics.rejected = resumeList.value.filter(r => r.status === 'rejected').length
  statistics.needs_revision = resumeList.value.filter(r => r.status === 'needs_revision').length
}

// 获取完成度状态
const getCompletionStatus = (rate: number): 'success' | 'warning' | 'exception' => {
  if (rate >= 80) return 'success'
  if (rate >= 60) return 'warning'
  return 'exception'
}

// 处理筛选变化
const handleFilterChange = () => {
  pagination.page = 1
  fetchReviewedResumeList()
}

// 处理搜索
const handleSearch = () => {
  // 防抖处理
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleFilterChange()
  }, 500)
}

let searchTimer: NodeJS.Timeout

// 重置筛选条件
const resetFilters = () => {
  filters.status = ''
  filters.dateRange = null
  filters.keyword = ''
  pagination.page = 1
  fetchReviewedResumeList()
}

// 刷新列表
const refreshList = () => {
  fetchReviewedResumeList()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchReviewedResumeList()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchReviewedResumeList()
}

// 处理预览
const handlePreview = (resume: Resume) => {
  currentResume.value = resume
  showPreviewDialog.value = true
}

// 处理查看审核详情
const handleViewReview = (resume: Resume) => {
  currentResume.value = resume
  showReviewDialog.value = true
}

// 获取状态描述
const getStatusDescription = (status: string): string => {
  switch (status) {
    case 'approved':
      return '简历审核通过，符合要求'
    case 'rejected':
      return '简历审核未通过，需要重新制作'
    case 'needs_revision':
      return '简历需要修改，请根据意见调整'
    default:
      return ''
  }
}

// 获取处理时长
const getProcessingDuration = (resume: Resume): string => {
  if (!resume.created_at || !resume.reviewed_at) {
    return '未知'
  }

  const created = new Date(resume.created_at)
  const reviewed = new Date(resume.reviewed_at)
  const diffMs = reviewed.getTime() - created.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  const diffHours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))

  if (diffDays > 0) {
    return `${diffDays}天${diffHours}小时`
  } else if (diffHours > 0) {
    return `${diffHours}小时`
  } else {
    const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
    return `${diffMinutes}分钟`
  }
}

// 生命周期
onMounted(() => {
  fetchReviewedResumeList()
})
</script>

<style lang="scss" scoped>
.reviewed-resume-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0;
    }
  }

  .filter-bar {
    margin-bottom: 20px;
    padding: 16px;
    background: var(--fill-color-extra-light);
    border-radius: 6px;
  }

  .statistics {
    margin-bottom: 20px;
    padding: 16px;
    background: var(--fill-color-light);
    border-radius: 6px;
  }

  .resume-title {
    display: flex;
    align-items: center;
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }

  .review-detail {
    .detail-card {
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        h4 {
          margin: 0;
          color: var(--text-color-primary);
          font-size: 16px;
          font-weight: 600;
        }
      }
    }

    .title-info {
      display: flex;
      align-items: center;

      .title-text {
        font-weight: 500;
        color: var(--text-color-primary);
      }
    }

    .completion-info {
      display: flex;
      align-items: center;
    }

    .status-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .status-desc {
        color: var(--text-color-secondary);
        font-size: 12px;
      }
    }

    .time-info,
    .reviewer-info,
    .duration-info {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-icon {
        color: var(--color-primary);
      }
    }

    .comments-content {
      .comments-text {
        padding: 16px;
        background: var(--fill-color-extra-light);
        border-radius: 6px;
        border-left: 4px solid var(--color-primary);
        line-height: 1.6;
        color: var(--text-color-primary);
        white-space: pre-wrap;
      }
    }

    .timeline-content {
      .timeline-title {
        display: flex;
        align-items: center;
        gap: 6px;
        font-weight: 500;
        color: var(--text-color-primary);
        margin-bottom: 4px;

        .el-icon {
          font-size: 14px;
        }
      }

      .timeline-desc {
        color: var(--text-color-secondary);
        font-size: 13px;
        line-height: 1.4;
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.el-table--default :deep() .cell{
  padding: 0 5px;
}
</style>
